<?php

namespace app\admin\controller\unilive;

use app\common\controller\Backend;
use EasyWeChat\Factory;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 临时素材
 *
 * @icon fa fa-circle-o
 */
class Media extends Backend
{

    /**
     * Media模型对象
     * @var \app\admin\model\unilive\Media
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\unilive\Media;
        $this->view->assign("typeList", $this->model->getTypeList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {

                $curl = curl_init();
                curl_setopt($curl, CURLOPT_URL, cdnurl($params['path'], true));
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
                $info = curl_exec($curl);
                curl_close($curl);
                $newFileName = RUNTIME_PATH.'temp/unilive/'; //保存的本地地址
                if (!file_exists($newFileName)) {
                    mkdir($newFileName);
                }
                $newFileName = $newFileName.time().'.png';
                $fp = @fopen($newFileName, "a");
                @fwrite($fp, $info);
                @fclose($fp);

                // 上传到微信临时素材
                $app = Factory::miniProgram(get_addon_config('unilive'));
                $media = $app->media->upload($params['type'], $newFileName);
                @unlink($newFileName);

                if (empty($media) || empty($media['media_id'])) {
                    throw new Exception('上传失败');
                }
                $params['media_id'] = $media['media_id'];
                $params['passtime'] = time() + 259200;

                $result = false;
                Db::startTrans();

                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
}
